<template>
  <div>
    <div class="header flex-row">
      <span class="flex-row-ver cur"><i>1</i>门店信息</span>
      <span class="flex-row-ver" @click="toPage(2)"><i>2</i>资质信息</span>
      <span class="flex-row-ver" @click="toPage(3)"><i>3</i>合作方案</span>
    </div>
    <el-row class="item" id="laoding-aear">
      <el-form :model="params" :rules="rules" ref="ruleForm" label-width="110px" size="small">
        <el-form-item label="所属区域" prop="agentid" v-if="$store.state.showAgent">
          <el-select style="width: 230px" @change="clearAddress()" v-model="params.agentid" filterable placeholder="--区域--">
            <el-option v-for="items in restaurants" :key="'restaurants'+items.id" :label="items.name" :value="items.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属BD(选填)" :disabled="$store.state.type === 5">
          <el-select style="width: 230px" v-model="params.bdid" filterable clearable placeholder="--所属BD--">
            <el-option v-for="items in businessDevelopmentList" :key="'businessDevelopmentList'+items.id" :label="items.name" :value="items.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="门店名称" prop="name">
          <el-input style="width: 710px;" v-model="params.name" placeholder="请与门店照上的名称保持一致" clearable />
        </el-form-item>
        <el-form-item label="外卖电话" required style="margin-bottom: 0">
          <el-row type="flex" v-for="(item,index) in params.wmMobile" :key="'wmMobile'+index">
            <el-form-item :prop="'wmMobile.' + index" :rules="[{required: true, message: '外卖电话未填写', trigger: 'blur'}]">
              <el-input style="width: 230px" v-model="params.wmMobile[index]" placeholder="请输入外卖联系人电话" clearable />
            </el-form-item>
            <el-form-item style="margin-left: 120px">
              <el-button type="text" class="el-text-success" v-if="index == '0'" :disabled="params.wmMobile.length >=5"
                         @click="params.wmMobile.push('')">添加外卖电话({{params.wmMobile.length}}/5个)
              </el-button>
              <el-button class="el-text-danger" v-else type="text" @click="params.wmMobile.splice(index,1)">删除</el-button>
            </el-form-item>
          </el-row>
        </el-form-item>

        <el-form-item label="联系人姓名" prop="bossName">
          <el-input style="width: 230px" v-model="params.bossName" placeholder="请输入商家联系人姓名" clearable />
        </el-form-item>

        <el-form-item label="商家电话" prop="mobile">
          <el-input style="width: 230px" v-model="params.mobile" placeholder="请输入联系人电话" clearable /><span style="color: #999;"> (登录账号)</span>
        </el-form-item>

        <el-form-item label="登录密码" prop="password">
          <el-input type="password" style="width: 230px" v-model="params.password" placeholder="请输入商家登录密码密码" clearable />
        </el-form-item>

        <el-form-item label="门店分类" required style="margin-bottom: 0">
          <el-row type="flex">
            <el-form-item prop="mainClassId">
              <el-cascader style="width: 230px" expand-trigger="hover" clearable :options="classlist"
                :show-all-levels="false" placeholder="主分类，必选" v-model="params.mainClassId" :props="classlistAlias" />
            </el-form-item>
        
            <el-form-item prop="subClassId1">
              <el-cascader style="margin-left: 10px;width: 230px" expand-trigger="hover" clearable :options="classlist"
                :show-all-levels="false" placeholder="次分类，非必选" v-model="params.subClassId1" :props="classlistAlias" />
            </el-form-item>
        
            <el-form-item prop="subClassId2">
              <el-cascader style="margin-left: 10px;width: 230px" expand-trigger="hover" clearable :options="classlist"
                :show-all-levels="false" placeholder="次分类，非必选" v-model="params.subClassId2" :props="classlistAlias" />
            </el-form-item>
          </el-row>
        </el-form-item>

        <el-form-item label="工作日" prop="worktoday">
          <el-checkbox-group v-model="params.worktoday" style="height: 32px">
            <el-checkbox style="margin-left: 0;margin-right: 30px;" v-for="(week,index) in weeks" :label="index+1"
              :key="'week'+index">{{week}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="应用时间" required>
          <el-radio v-model="timeType" label="1">24小时</el-radio>
          <el-radio v-model="timeType" label="2">自定义</el-radio>
        </el-form-item>
        <el-form-item v-if="timeType== '2'" prop="firstTime" label="营业时间一">
          <el-time-select style="width: 230px" placeholder="起始时间" v-model="params.firstTime[0]"
            :picker-options="{start: '00:00',step: '00:30',end: '24:00'}" />
          <span>-</span>
          <el-time-select style="width: 230px" placeholder="结束时间" v-model="params.firstTime[1]"
            :picker-options="{start: '00:00',step: '00:30',end: '24:00', minTime: params.firstTime[0]}" />
        </el-form-item>
        <el-form-item v-if="timeType== '2'" label="营业时间二">
          <el-time-select style="width: 230px" placeholder="起始时间" v-model="params.secondTime[0]"
            :picker-options="{start: '00:00',step: '00:30',end: '24:00'}" />
          <span>-</span>
          <el-time-select style="width: 230px" placeholder="结束时间" v-model="params.secondTime[1]"
            :picker-options="{start: '00:00',step: '00:30',end: '24:00', minTime: params.secondTime[0]}" />
        </el-form-item>
        <el-form-item v-if="timeType=='2'" label="营业时间三">
          <el-time-select style="width: 230px" placeholder="起始时间" v-model="params.thirdTime[0]"
            :picker-options="{start: '00:00',step: '00:30',end: '24:00'}" />
          <span>-</span>
          <el-time-select style="width: 230px" placeholder="结束时间" v-model="params.thirdTime[1]"
            :picker-options="{start: '00:00',step: '00:30',end: '24:00', minTime: params.thirdTime[0]}" />
        </el-form-item>
        <el-form-item label="门店地址" prop="latitude">
          <el-input style="width: 710px" :value="params.provinceName + params.cityname + params.countyname" readonly placeholder="请点击选择地址" >
            <el-button slot="append" type="success" @click="choseMap()">地图选址</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="门牌号、楼层等" prop="address">
          <el-input style="width: 710px" ref="address" v-model="params.address" placeholder="门店位置补充，如门店热点名称、门牌号、楼层等" />
        </el-form-item>
        <el-form-item label="门店照片" prop="faceImage">
          <div class="upimg-wrap">
            <div class="list flex-row">
              <pt-upload class="update" :size="5" :upLoadImg="params.faceImage" @getUpLoad="getUpLoad1" />
              <div class="msg">
                上传门脸照片。<br/>门脸照需拍出完整的门匾、门框、需再餐厅开门营业状态下完成拍摄。(建议正对门店2米处拍摄，图片支持JPG、JPEG、PNG格式，<span style="color:#e6a23c">大小不超过5M</span>)
              </div>
              <div class="demo"><img src="assets/img/demo1.png" /></div>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="innerImageLs" label="店内照片">
          <div class="upimg-wrap">
            <div class="list">
              <div class="flex-row" style="padding-bottom: 10px;border-bottom: 1px solid #eee">
                <div class="msg">
                  上传店内照片。<br/>店内照需正式反应用餐环境。(环境覆盖收银台、用餐桌椅。图片支持JPG、JPEG、PNG格式，
                  <span style="color:#e6a23c">大小不超过5M,不超过5张</span>)
                </div>
                <div class="demo"><img src="assets/img/demo2.png" /></div>
              </div>
              <pt-uploads class="update-list" style="padding-top: 10px" :size="5" :limit="5" :upLoadImg="params.innerImage"
                @getUploadList="getUpLoad2" @deleteImage="deleteInnerImg" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="门店LOGO" prop="imgpath">
          <div class="upimg-wrap">
            <div class="list flex-row">
              <pt-upload class="update" :size="0.5" :upLoadImg="params.imgpath" @getUpLoad="getUpLoad3" />
              <div class="msg">
                上传LOGO照片。<br/>上传清楚的门店广告logo图片。(建议尺寸200*200或以上 图片支持JPG、JPEG、PNG格式，<span style="color:#e6a23c">大小不超过500k</span>)
              </div>
              <div class="demo"><img src="assets/img/demo3.png" /></div>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="issubmitLoading" @click="submitForm('ruleForm')">保存并到下一步</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <div v-if="infoLoading" class="info-loading-addShop"></div>
  </div>
</template>
<script>
  import {toTimeForHs, toTimeForYHs } from '@/utils/ptkc'
  import { businessDevelopment, businessTypeList, agentInfo } from '@/api/busnt.js'
  export default {
    data() {
      return {
        params: {
          agentid: '',//所属区域id
          bdid: null, // BD
          name: '',//商家名称
          wmMobile: [''], //外卖电话
          bossName: '', //联系人姓名
          mobile: '', //商家电话
          mainClassId: [], //分类分类id
          subClassId1: [],//分类分类id
          subClassId2: [],//分类分类id
          worktoday: [1, 2, 3, 4, 5, 6, 7], // 工作日
          firstTime: [],//时间一
          secondTime: [],//时间二
          thirdTime: [],//时间三
          provinceName: '', //省id
          cityname: '',//城市Id
          countyname: '',//县区Id
          address: '',//详细地址
          longitude: '',//精度
          latitude: '',//维度
          faceImage: '',//门脸照片
          password: '',// 登录密码
          innerImage: [],//店内照片
          innerImageLs: [], // 店内找临时数据
          imgpath: '' //门店logo
        },
        classlistAlias: { children: 'subList', value: "id", label: "name" },
        infoLoading: false, //页面等待info数据
        classlist: [],//分类列表
        businessDevelopmentList: [], //BD列表
        issubmitLoading: false, // 提交等待
        weeks: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        timeType: '1',  //是否自定义时间
        innerImage: [], // 临时店内图片
        distrange: null, // 围栏
        searchName: '', // 模糊查询数据
        rules: {
          agentid: [{required: true, message: '请选择区域', trigger: ['blur', 'change']}],
          name: [{required: true, message: '门店名称未填写', trigger: 'blur'}],
          bossName: [{required: true, message: '商家联系人姓名未填写', trigger: 'blur'}],
          mobile: [{required: true, message: '商家电话未填写', trigger: 'blur'}],
          password: [{required: true, message: '请输入商家登录密码', trigger: 'blur'},{min: 6, max: 32, message: '密码长度限制6-32位', trigger: 'blur'}],
          mainClassId: [{required: true, message: '主分类未选', trigger: 'change'}],
          worktoday: [{type: 'array', required: true, message: '最少选择一天工作日', trigger: 'change'}],
          firstTime: [{type: 'array', required: true, message: '最少选择一个时间段', trigger: 'change'}],
          countyname: [{required: true, message: '请选择省市区', trigger: 'change'}],
          latitude: [{required: true, message: '请选址门店位置', trigger: 'change'}],
          address: [{required: true, message: '详细地址不能为空', trigger: 'blur'}],
          faceImage: [{required: true, message: '请上传门脸照', trigger: 'change'}],
          innerImageLs: [{required: true, message: '请上次店内照片', trigger: 'change'}],
          imgpath: [{required: true, message: '请上传门店LOGO', trigger: 'change'}],
        }
      }
    },
    computed: {
      restaurants() { // 代理商数据
        return this.$store.state.agentList
      }
    },
    watch: {
      restaurants: {
        handler(val) {
          if (val && val.length) {
            if (val.length === 1 && !this.$route.query.id) { // 只有一个代理商 直接显示
              this.params.agentid = val[0].id
            }
          }
        },
        deep: true,
        immediate: true
      },
      'params.agentid': {
        handler(val) {
          if (val) {
            this.getAgentInfo(this.params.agentid)
            this.getBusinessDevelopment(val)
            this.getCategoryList(val)
          }
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      toPage(page) {
        let id = this.$route.query.id
        if (page == '2' && id) {
          this.$router.push({path: '/main/busnt/add2', query: {id: id}})
        } else if (page == '3' && id) {
          this.$router.push({path: '/main/busnt/add3', query: {id: id}})
        } else {
          this.$alert('请完善提交当前数据！')
        }
      },
      choseMap() { // 打开地图选址
        if (!this.params.agentid) {
          this.$alert('请先选一个区域')
          return false
        }
        const options = {
          searchName: this.searchName,
          province: this.params.provinceName + this.params.cityname + this.params.countyname,
          lat: this.params.latitude,
          lng: this.params.longitude,
          distrange: this.distrange
        }
        if (isChina) {
          this.$gaodeMap(options, e => {
            this.params.provinceName = e.province
            this.params.cityname = ''
            this.params.countyname = ''
            this.params.longitude = e.lng
            this.params.latitude = e.lat
            this.$refs['address'].focus()
          })
        } else {
          this.$googleMap(options, e => {
            this.params.provinceName = e.province
            this.params.cityname = ''
            this.params.countyname = ''
            this.params.longitude = e.lng
            this.params.latitude = e.lat
            this.$refs['address'].focus()
          })
        }
      },
      clearAddress() { // 清楚定位
        this.params.provinceName = ''
        this.params.cityname = ''
        this.params.countyname = ''
        this.params.longitude = ''
        this.params.latitude = ''
        this.params.address = ''
        this.distrange = null
        this.params.bdid = null
        this.params.mainClassId = []
        this.params.subClassId1 = []
        this.params.subClassId2 = []
      },
      getCategoryList(agentId) { //获取分类数据
        businessTypeList({ agentId }).then(res => {
          if (res.success) {
            this.classlist = res.data
            this.classlist.forEach((item, index) => {
              if (item.subList.length == 0) {
                delete this.classlist[index]
              } else {
                item.subList.forEach((list, index1) => {
                  delete list.subList
                })
              }
            })
          }
        })
      },
      getUpLoad1(img) { // 上传区域店铺首页图片
        this.params.faceImage = img
      },
      getUpLoad2(imgs) { // 本地添加店内图片
        this.params.innerImageLs.push({name: imgs.name, url: `http://image.jiaowawang.cn/${imgs.url}`})
      },
      deleteInnerImg(img) { // 本地删除店内图片
        const index = this.params.innerImageLs.findIndex(item => {
          return `http://image.jiaowawang.cn/${img}` === `${item.url}`
        })
        if (index > -1) this.params.innerImageLs.splice(index, 1)
      },
      getUpLoad3(img) { // 上传区域店铺首页图片
        this.params.imgpath = img
      },
      submitForm(formName) { //提交数据
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.params }
            if (this.timeType == '1') {
              params.firstTime = ''
              params.secondTime = ''
              params.thirdTime = ''
            }
            params.firstTime = toTimeForYHs(params.firstTime)
            params.secondTime =toTimeForYHs(params.secondTime)
            params.thirdTime = toTimeForYHs(params.thirdTime)
            params.mainClassId = params.mainClassId[1]
            params.subClassId1 = params.subClassId1.length > 0 ? params.subClassId1[1] : ''
            params.subClassId2 = params.subClassId2.length > 0 ? params.subClassId2[1] : ''
            const innerImage = []
            if (this.params.innerImageLs.length) {
              this.params.innerImageLs.forEach(item => {
                innerImage.push(item.url.replace('http://image.jiaowawang.cn/', ''))
              })
            }
            params.bdname = ''
            if (params.bdid) params.bdname = this.businessDevelopmentList[this.businessDevelopmentList.findIndex(i => i.id === params.bdid)].name
            delete params.innerImageLs
            params.innerImage = innerImage.length ? innerImage.join(',') : ''
            params.wmMobile = params.wmMobile.length > 0 ? params.wmMobile.join(',') : ''
            params.worktoday = params.worktoday.join(',')
            params.miniImgpath = params.imgpath
            this.issubmitLoading = true
            if (this.$route.query.id) {
              params.id = this.$route.query.id
              params.updateflage = 1 //提交第一步标记
              this.$http.post('/server/business/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '提交成功'})
                  this.$router.push({path: '/main/busnt/add2', query: { id: params.id }})
                }
              }).finally(() => { this.issubmitLoading = false })
            } else {
              this.$http.post('/server/business/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '提交成功'})
                  this.$router.push({path: '/main/busnt/add2', query: {id: res.data.data.businessId}})
                }
              }).finally(() => { this.issubmitLoading = false })
            }
          } else {
            this.$alert('有不合法的输入，请检查页面修改再提交')
            return false
          }
        })
      },
      getShopList() { //显示数据
        const params = {id: this.$route.query.id}
        this.infoLoading = true
        this.$http.get('/server/business/info?' + this.qs.stringify(params), {headers: {isCancel: true}}).then(res => {
          if (res.data.success) {
            const row = res.data.data
            const toArray = function (str) { // 转整形数组
              const array = []
              str.split(',').forEach(data => {
                array.push(+data)
              })
              return array
            }
            this.params.agentid = row.agentid || ''
            this.params.name = row.name || ''
            this.params.wmMobile = row.wmMobile ? (row.wmMobile.indexOf(',') > -1 ? row.wmMobile.split(',') : [row.wmMobile]) : ['']
            let innerImgs = row.innerImage ? row.innerImage.split(',') : []
            if (innerImgs.length) {
              innerImgs = innerImgs.map((item, index) => {
                return {name: `已保存的图片${index + 1}.jpg`, url: `http://image.jiaowawang.cn/${item}`}
              })
            }
            this.params.innerImage = innerImgs
            this.params.innerImageLs = innerImgs
            this.params.faceImage = row.faceImage || ''
            this.params.imgpath = row.imgpath || ''
            this.params.bossName = row.bossName || ''
            this.params.mobile = row.mobile || ''
            this.params.password = row.password || ''
            this.params.bdid = row.bdid
            this.params.mainClassId = row.firstClass ? toArray(row.firstClass) : []
            this.params.subClassId1 = row.secondClass ? toArray(row.secondClass) : []
            this.params.subClassId2 = row.thirdClass ? toArray(row.thirdClass) : []
            this.params.worktoday = row.worktoday ? toArray(row.worktoday) : []
            this.params.firstTime = toTimeForHs(row.firstTime)
            this.params.secondTime = toTimeForHs(row.secondTime)
            this.params.thirdTime = toTimeForHs(row.thirdTime)
            this.params.provinceName = row.provinceName || ''
            this.params.cityname = row.cityname || ''
            this.params.countyname = row.countyname || ''
            this.params.address = row.address || ''
            this.params.longitude = row.longitude || ''
            this.params.latitude = row.latitude || ''
            this.params.agentid = row.agentid
            if (this.params.firstTime.length)this.timeType = '2'
            else this.timeType = '1'
          }
        }).finally(() => { this.infoLoading = false })
      },
      getAgentInfo(id) { //定位代理商
        agentInfo({ id }).then((res) => {
          if (res.success) {
            this.searchName = (res.data.province || '') + (res.data.cityname || '') + (res.data.countyname || '')
            if (res.data.flage === 2) {
              if (res.data.distrange) {
                this.distrange = res.data.distrange
              } else {
                if (this.$store.state.showAgent) {
                  this.$confirm(`此区域为绘制区域，是否前往完善？`).then(() => {
                    this.$router.push({
                      path: '/main/company/add',
                      query: { id: this.params.agentid }
                    })
                  }).catch(() => {
                    this.params.agentid = ''
                  })
                } else{
                  this.$message.error('区域信息未完善，请联系平台完善地图区域信息')
                  this.$router.back()
                }
                return false
              }
            }
          } 
        })
      },
      getBusinessDevelopment(agentId) { // 获取BD数据
        businessDevelopment({ agentId }).then(res => {
          if (res.success) {
            this.businessDevelopmentList = res.data
            if (this.$store.state.type === 5) this.params.bdid = this.businessDevelopmentList[0].id || ''
          }
        })
      }
    },
    mounted() {
      if (this.$route.query.id) {
        this.getShopList()
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '/css/header.scss';
  @import '/css/add1.scss';
</style>
<style lang="scss">
  .bus-pot-chose{
    position: relative;
    background: #fff;
    .btn{
      width: 60px;
      height: 20px;
      text-align: center;
      overflow: hidden;
      line-height: 20px;
      border-radius: 4px;
      border: 1px solid #eee;
    }
    .hover{
      position: absolute;
      right: 0;
      top: -20px;
      background: #fff;
      border: 1px solid #ccc;
      display: none;
    }
    .btn:hover .hover{
      display: block;
    }
  }
</style>
